package com.we.risk.registerorigin.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.we.risk.registerorigin.table.TableUserSource;

public class TagUserSource {
    public long uid;
    public String utm_source;
    public String keyword;
    public long update_time;
    //    public String advert;
    //    public String ad_group;

    public TagUserSource(long uid, String utm_source, String keyword, long update_time) {
        this.uid = uid;
        this.utm_source = utm_source;
        this.keyword = keyword;
        this.update_time = update_time;
        //        this.ad_group = ad_group;
        //        this.advert = advert;
    }

    public static TagUserSource init(long uid) {
        return new TagUserSource(uid, "", "", Long.MAX_VALUE);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserSource.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserSource>> input =
                tableEnv.toRetractStream(tableRes, TableUserSource.class);

        SingleOutputStreamOperator<String> out =
                input.filter(
                                new FilterFunction<Tuple2<Boolean, TableUserSource>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserSource> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserSource-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserSource>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserSource> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserSource>, String>() {
                                    ValueState<TagUserSource> tagUserSourceVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tagUserSourceVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagUserSource>(
                                                                        "TagUserSourceVState",
                                                                        TagUserSource.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserSource> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        long update_time = value.f1.getUpdate_time();

                                        TagUserSource tmpState = tagUserSourceVState.value();
                                        TagUserSource curState =
                                                tmpState == null
                                                        ? TagUserSource.init(uid)
                                                        : tmpState;
                                        if (update_time < curState.update_time) {
                                            String origin_source = value.f1.getOrigin_source();
                                            String utm_source = null;
                                            String key_word = null;
                                            String account = null;
                                            if (origin_source.contains("_")) {
                                                String[] split = origin_source.split("_");
                                                if (split.length == 2) {
                                                    key_word = split[0];
                                                    account = split[1];
                                                }
                                            } else {
                                                key_word = origin_source;
                                            }

                                            if (account == null || account.equals("3728570")) {
                                                utm_source = "App Store-asa";
                                            } else {
                                                utm_source = "App Store-" + account;
                                            }

                                            JSONObject outJson = new JSONObject();

                                            outJson.put("uid", uid);
                                            outJson.put("update_time", update_time);
                                            outJson.put("key_word", key_word);
                                            outJson.put("utm_source", utm_source);
                                            outJson.put("ad_group", null);
                                            outJson.put("advert", null);
                                            out.collect(
                                                    outJson.toString(
                                                            SerializerFeature.WriteMapNullValue));

                                            curState.update_time = update_time;
                                            curState.utm_source = utm_source;
                                            curState.keyword = key_word;
                                            tagUserSourceVState.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public String getUtm_source() {
        return utm_source;
    }

    public String getKeyword() {
        return keyword;
    }

    public long getUpdate_time() {
        return update_time;
    }
}
